package com.formula.distribution.encrypt.advice;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.formula.distribution.encrypt.annotation.Encrypt;
import com.formula.distribution.encrypt.config.EncryptProperties;
import com.formula.distribution.encrypt.encrypt.AbstractEncrypt;
import com.formula.distribution.encrypt.exception.EncryptException;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author:luyanan
 * @email:luyanan0718@163.com
 * @date 2018/12/15 14:27
 * @introduce 请求响应解密
 **/
@Slf4j
@Service
@DependsOn("encrypt")
@RequiredArgsConstructor
@ControllerAdvice
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private ObjectMapper objectMapper = new ObjectMapper();


    @Autowired
    EncryptProperties encryptProperties;


    //    @NonNull
    @Autowired
    private AbstractEncrypt abstractEncrypt;


    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        if (methodParameter.getMethod().isAnnotationPresent(Encrypt.class) && !encryptProperties.isDebug()) {
            try {
                String content = o.toString();
                if (StrUtil.isBlank(encryptProperties.getKey())) {
                    throw new EncryptException("请先配置 spring.formula.encrypt.key");
                }
                String result = abstractEncrypt.encrypt(content, encryptProperties.getKey());
                return result;

            } catch (Exception e) {
                log.error("加密异常", e);
            }


        }


        return o;
    }
}
